
//
//  Created by meilbn on 6/11/16.
//  Copyright © 2016 xiaofulon. All rights reserved.
//

#import "OPMovieViewController.h"
#import <MJRefresh/MJRefresh.h>
#import "OPMovieListItemCCell.h"
#import "MTLJSONAdapter.h"
#import "OPMovieListItem.h"
#import <MJExtension.h>
#import "OPMovieDetailsViewController.h"


@interface OPMovieViewController ()<UICollectionViewDelegateFlowLayout,UICollectionViewDataSource>
/**collectionView*/
@property (nonatomic, strong) UICollectionView *collectionView;
/**模型数据*/
@property (nonatomic, strong) NSMutableArray *dataSource;
@end

@implementation OPMovieViewController

NSString *const kOPMovieListItemCCellID = @"OPMovieListItemCCellID";

- (void)viewDidLoad {
    [super viewDidLoad];
    // 注册cell
    [self.collectionView registerClass:[OPMovieListItemCCell class] forCellWithReuseIdentifier:kOPMovieListItemCCellID];
    // 添加刷下拉刷新控件
    [MLBUIFactory addMJRefreshTo:_collectionView target:self refreshAction:nil loadMoreAction:@selector(loadMoreMovieItem)];
    // 从cache中取数据
    [self loadCacheDataSource];
    // 请求数据
    [self requestMovieListWithOffser:0];

}

// 模型数据懒加载
- (NSMutableArray *)dataSource{
    if (_dataSource == nil) {
        
        _dataSource = [NSMutableArray array];
    }
    
    return  _dataSource ;
}
// 懒加载collectionView
-(UICollectionView *)collectionView{
    if (_collectionView == nil) {
        // 使用流水布局
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        // 设置cell的size
        layout.itemSize = CGSizeMake(SCREEN_WIDTH, 140);
        // 设置行间距
        layout.minimumLineSpacing = 5;
        // 创建collectionView
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
        // 设置collectionView背景颜色
        collectionView.backgroundColor = [UIColor colorWithWhite:229 / 255.0 alpha:1];
        // 设置数据源和代理
        collectionView.dataSource = self;
        collectionView.delegate = self;
        // 将collectionView添加到控制器的View
        [self.view addSubview:collectionView];
        // 设置collectionView的位置
        [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        
        _collectionView = collectionView ;
    }
    return _collectionView ;
}

// 先从沙盒中获取数据
- (void)loadCacheDataSource{
    // 解档数据
    id cacheMovieList = [NSKeyedUnarchiver unarchiveObjectWithFile:MLBCacheMovieListFilePath];
    // 如果有数据就赋值给dataSource
    if (cacheMovieList) {
        self.dataSource = cacheMovieList;
        // 刷新数据
        [_collectionView reloadData];
    }
}
// 加载更多数据
- (void)loadMoreMovieItem{
    
    NSInteger offset = self.dataSource.count + (30 - (self.dataSource.count % 30));
    [self requestMovieListWithOffser:offset];
}

// 发送请求
- (void)requestMovieListWithOffser:(NSInteger)offset {
    // 发送请求
    [MLBHTTPRequester requestMovieListWithOffer:offset success:^(id responseObject) {

        if ([responseObject[@"res"] integerValue] == 0) {
            if (offset == 0) {
                [self.dataSource removeAllObjects];
            }
            // MJExtenstion模型转换,将字典数组转换为模型数组
            NSArray *movieArr = [OPMovieListItem mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            // 将得到的模型数组添加到总模型数组,刷新表格
            [self.dataSource addObjectsFromArray:movieArr];
            [self.collectionView reloadData];
            // 结束刷新,判断是否还有下一页.
            [self endRefreshingScrollView:_collectionView hasMoreData:movieArr.count >= 30];
            // 开启子线程,存档数据
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                [NSKeyedArchiver archiveRootObject:self.dataSource toFile:MLBCacheMovieListFilePath];
            });
        }
            
     }fail:^(NSError *error) {
            // 请求失败,结束刷新
            [self endRefreshingScrollView:_collectionView hasMoreData:YES];
        }];
}


#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.dataSource.count ;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    // 从缓存池中取cell
    OPMovieListItemCCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kOPMovieListItemCCellID forIndexPath:indexPath];
    // 将模型数据传给cell
    [(OPMovieListItemCCell *)cell configureCellWithMovieListItem:self.dataSource[indexPath.row] atIndexPath:indexPath];
    
    return cell ;
}

#pragma mark - UICollectionViewDelegateFlowLayout

// cell消失时,停止计时
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    
    [(OPMovieListItemCCell *)cell stopCountDownIfNeeded];
}
// 选中cell 时跳转到细节控制器
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    OPMovieDetailsViewController *movieDetailsViewController = [[OPMovieDetailsViewController alloc] init];
    movieDetailsViewController.moviListItem = self.dataSource[indexPath.row];
    [self.navigationController pushViewController:movieDetailsViewController animated:YES];
}
@end
